package phase01.module4.code.question4;

import java.io.*;
import java.net.Socket;

public class ClientBinder {
    public void request(String username, String password) {
        String msg = "login";
        String rt;
        try (Socket s = new Socket("127.0.0.1", 8888);
             PrintStream ps = new PrintStream(s.getOutputStream());
             BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
             ObjectOutputStream oo = new ObjectOutputStream(s.getOutputStream());
             ObjectInputStream oi = new ObjectInputStream(s.getInputStream())
        ) {
            while (true) {
                ps.println(msg);
                if ("bye".equals(msg)) {
                    System.out.println("结束服务！");
                    System.out.println("==============================================================================================");
                    break;
                }
                rt = br.readLine();
                System.out.println(rt);
                UserMessage um = new UserMessage("login", new User(username, password));
                System.out.println("发送登录信息：" + um);
                oo.writeObject(um);
                UserMessage umRes = (UserMessage) oi.readObject();
                if ("success".equals(umRes.getMessageType())) {
                    System.out.println("登录成功！");
                } else {
                    System.out.println("登录失败！");
                }
                msg = "bye";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
